package controllers

import (
	"github.com/astaxie/beego"
	"net/http"
)

// BaseController 基础控制器
type BaseController struct {
	beego.Controller
}

// Result 返回值
type Result map[string]interface{}

// @title 未授权返回
func (this *BaseController) Unauthorized(message string) {
	if message == "" {
		message = "请先登录"
	}
	this.JsonResponse(http.StatusUnauthorized, message, Result{})
}

// @title 成功返回
func (this *BaseController) Success(message string, data interface{}) {
	this.JsonResponse(http.StatusOK, message, data)
}

// @title 失败返回
func (this *BaseController) Fail(message string, data interface{}) {
	this.JsonResponse(http.StatusInternalServerError, message, data)
}

// @title json返回
func (this *BaseController) JsonResponse(code int, message string, data interface{}) {
	if data == nil {
		data = Result{}
	}

	this.Ctx.ResponseWriter.WriteHeader(http.StatusOK)

	this.Data["json"] = Result{
		"code":    code,
		"message": message,
		"data":    data,
	}
	this.ServeJSON()
}
